﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace ExcelFileQueryTool
{
    public sealed class DatabaseService
    {
        public string DBName { get; private set; }

        public string ConnectionString { get; private set; }

        public DatabaseService(string connStr, string dbName)
        {
            if (string.IsNullOrEmpty(dbName))
                throw new ArgumentNullException("dbName");

            DBName = dbName;
            ConnectionString = connStr;
        }

        public bool IsOnline()
        {
            string sql = "select state_desc from sys.databases where name='" + DBName + "'";

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                var state = SqlMapper.ExecuteScalar<string>(conn, sql);

                return "ONLINE".Equals(state, StringComparison.InvariantCultureIgnoreCase);
            }
        }

        public void SetOnline()
        {
            string sql = "ALTER DATABASE " + DBName + " SET ONLINE";

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                SqlMapper.Execute(conn, sql);
            }
        }

        public void SetOffline()
        {
            string sql = "ALTER DATABASE " + DBName + " SET OFFLINE WITH ROLLBACK IMMEDIATE";

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                SqlMapper.Execute(conn, sql);
            }
        }
    }
}
